import telnetlib
import time

class TelnetClient():
    def __init__(self,):
        self.tn = telnetlib.Telnet()
    
    def login_host(self, host_ip, username, password, changepws):
        try:
            self.tn.open(host_ip, port=23)
        except:
            return False
        self.tn.read_until(b'Username:', timeout=10)
        self.tn.write(username.encode('ascii') +b'\n')
        self.tn.read_until(b'Password:', timeout=10)
        self.tn.write(password.encode('ascii') +b'\n')
        self.tn.read_until(b'The passord needs to be changed. Change now? [Y/N]:', timeout=10)
        self.tn.write(changepws.encode('ascii') +b'\n')
        time.sleep(2)
        command_result = self.tn.read_very_eager().decode('ascii')
        if 'Login incorrect' not in command_result:
            print('%sSuccess'%host_ip)
            return True
        else:
            print("Fail login")
            return False

    def execute_some_command(self, command, interval = 0.5):
        self.tn.write(command.encode('ascii')+b'\n')
        time.sleep(interval)
        command_result = self.tn.read_very_eager().decode('ascii')
        print("Result: \n%s" % command_result)

    def logout_host(self):
        self.tn.write(b"exit\n")